package com.atguigu.juc.cas;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author yanglin
 * @create 2024-01-25 16:12 星期四
 * description:
 */
public class AtomicStampedDemo {
    
    public static void main(String[] args) {
        Book javaBook = new Book(1, "javaBook");
        AtomicStampedReference<Book> stampedReference = new AtomicStampedReference<>(javaBook,1);

        System.out.println(stampedReference.getReference() + "\t" + stampedReference.getStamp());

        Book mySQL = new Book(2, "mySQL");
        //返回值表示是否修改成功
        boolean b = stampedReference.compareAndSet(javaBook, mySQL, stampedReference.getStamp(), stampedReference.getStamp() + 1);
        System.out.println(b + "\t" + stampedReference.getReference() + "\t" + stampedReference.getStamp());

        boolean b2 = stampedReference.compareAndSet(mySQL, javaBook, stampedReference.getStamp(), stampedReference.getStamp() + 1);
        System.out.println(b2 + "\t" + stampedReference.getReference() + "\t" + stampedReference.getStamp());
    }
}

class Book {
    
    private int id;
    
    private String bookName;

    Book() {
    }

    public Book(int id, String bookName) {
        this.id = id;
        this.bookName = bookName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bookName='" + bookName + '\'' +
                '}';
    }
}